package com.ezops.dtcc.model.dao;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;



import org.apache.log4j.Logger;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementSetter;

import com.ezops.dtcc.model.ReportingMessage;
import com.ezops.dtcc.rowmapper.ReportingMessageRowMapper;

public class ReportingMessageDAO {
	private final static Logger LOGGER = Logger.getLogger(ReportingMessageDAO.class);
	private JdbcTemplate jdbcTemplate;

	public ReportingMessageDAO(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}
	
	public JdbcTemplate getJdbcTemplate() {
		return jdbcTemplate;
	}

	public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}

	public void insert(ReportingMessage reg) {
		String insertSql = "INSERT INTO REGULATORY (MSG_ID, MSG_TYPE, INSERT_TIMESTAMP, FPML) VALUES(?,?,?,?)";

		LOGGER.info("Inserting Record..Message ID ->" + reg.getMsgId());
		getJdbcTemplate().update(
				insertSql,
				new Object[] { reg.getMsgId(), reg.getMsgType(),
						reg.getInsertTimestamp(), reg.getFpml() });
	}

	private String getDate(Date date, String time) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String formattedDate = sdf.format(date);
		formattedDate += time;

		return formattedDate;
	}

	@SuppressWarnings("unchecked")
	public List<ReportingMessage> selectAllTrades(final Date startDate,
			final Date endDate) {
		String selectAllSql = "SELECT * FROM REGULATORY WHERE INSERT_TIMESTAMP BETWEEN TO_DATE(?, 'yyyy-MM-dd HH24:MI:SS') AND TO_DATE(?, 'yyyy-MM-dd HH24:MI:SS')";

		final String formattedStartDate = getDate(startDate, " 00:00:00");
		final String formattedEndDate = getDate(endDate, " 23:59:59");

		LOGGER.info("Getting All Trades for Dates ->" + formattedStartDate
				+ " And ->" + formattedEndDate);
		LOGGER.info("SQL Query ->" + selectAllSql);
		return jdbcTemplate.query(selectAllSql, new PreparedStatementSetter() {
			public void setValues(PreparedStatement ps) throws SQLException {
				ps.setString(1, formattedStartDate);
				ps.setString(2, formattedEndDate);
			}
		}, new ReportingMessageRowMapper());
	}
}
